import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store'
import router from '@/router'
import NProgress from 'nprogress'

// 创建axios实例
const request = axios.create({
  baseURL: '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 显示进度条
    NProgress.start()
    
    // 添加认证token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    return config
  },
  (error) => {
    NProgress.done()
    ElMessage.error('请求发送失败')
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    NProgress.done()
    
    const res = response.data
    
    // 根据业务状态码处理响应
    if (res.code === 200) {
      return res
    }
    
    // 处理业务错误
    switch (res.code) {
      case 400:
        ElMessage.error(res.message || '请求参数错误')
        break
      case 401:
        ElMessage.error('登录已过期，请重新登录')
        handleAuthError()
        break
      case 403:
        ElMessage.error('权限不足')
        break
      case 404:
        ElMessage.error('请求的资源不存在')
        break
      case 500:
        ElMessage.error(res.message || '服务器内部错误')
        break
      default:
        ElMessage.error(res.message || '操作失败')
    }
    
    return Promise.reject(new Error(res.message || '请求失败'))
  },
  (error) => {
    NProgress.done()
    
    console.error('Request error:', error)
    
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          ElMessage.error('登录已过期，请重新登录')
          handleAuthError()
          break
        case 403:
          ElMessage.error('权限不足')
          break
        case 404:
          ElMessage.error('请求的接口不存在')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        case 502:
          ElMessage.error('网关错误')
          break
        case 503:
          ElMessage.error('服务不可用')
          break
        case 504:
          ElMessage.error('网关超时')
          break
        default:
          ElMessage.error(data?.message || `请求失败 (${status})`)
      }
    } else if (error.code === 'ECONNABORTED') {
      ElMessage.error('请求超时，请检查网络连接')
    } else if (error.message === 'Network Error') {
      ElMessage.error('网络错误，请检查网络连接')
    } else {
      ElMessage.error('请求失败，请稍后重试')
    }
    
    return Promise.reject(error)
  }
)

// 处理认证错误
const handleAuthError = () => {
  const userStore = useUserStore()
  
  ElMessageBox.confirm(
    '登录状态已过期，您可以继续留在该页面，或者重新登录',
    '系统提示',
    {
      confirmButtonText: '重新登录',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    userStore.logout()
  }).catch(() => {
    // 用户选择取消，不做任何操作
  })
}

// 文件上传请求
export const uploadRequest = axios.create({
  baseURL: '/api',
  timeout: 60000,
  headers: {
    'Content-Type': 'multipart/form-data'
  }
})

// 文件上传拦截器
uploadRequest.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

uploadRequest.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response?.status === 401) {
      handleAuthError()
    } else {
      ElMessage.error('文件上传失败')
    }
    return Promise.reject(error)
  }
)

// 通用请求方法
export const get = (url, params = {}) => {
  return request({
    method: 'get',
    url,
    params
  })
}

export const post = (url, data = {}) => {
  return request({
    method: 'post',
    url,
    data
  })
}

export const put = (url, data = {}) => {
  return request({
    method: 'put',
    url,
    data
  })
}

export const del = (url, params = {}) => {
  return request({
    method: 'delete',
    url,
    params
  })
}

// 文件上传方法
export const upload = (url, formData, onProgress) => {
  return uploadRequest({
    method: 'post',
    url,
    data: formData,
    onUploadProgress: onProgress
  })
}

export default request